var Admin = function () {

    var menuEvents = function (menuNode) {

        var menuNode = menuNode ? menuNode : '.menu';

        $('body').undelegate(menuNode, 'click');
        $('body').delegate(menuNode, 'click', function () {

            var level = $(this).data('level');

            //var firstchild = firstchild ? firstchild : $('#menu'+level).children().first().children() ;

            var isLoad = $(this).data('loadchild');

            var menuid = $(this).data('id');

            action(level, isLoad, menuid, $(this), menuNode);

            return false;

        });
    }

    var _pages = function (options) {

        var $pages = $('#_pages');

        //获取总分页
        var total = $pages.data('total');

        //获取当前页码
        var page = $pages.data('page');

        //获取每页显示数量
        var nums = $pages.data('nums');

        //获取请求连接
        var src = $pages.data('src');

        //计算总页数
        var pageTotal = Math.ceil(total / nums);

        if( pageTotal < 2 )
            return false;

        var pageStr = '';

        if (page > 1) {

            pageStr += '<a href="javascript:;" data-src="' + src + '" data-page="1" class="num btn btn-default radius-none _page">首页</a>';
            pageStr += '<a href="javascript:;" data-src="' + src + '" data-page="' + (page - 1) + '" class="num btn btn-default radius-none _page">上一页</a>';

        }

        if (pageTotal <= 7) {

            for (var i = 1; i <= pageTotal; i++) {

                if (i == page) {

                    pageStr += '<span class="current btn btn-primary active radius-none">' + i + '</span>';

                } else {

                    pageStr += '<a href="javascript:;" data-src="' + src + '" data-page="' + i + '" class="num btn btn-default radius-none _page">' + i + '</a>';

                }

            }

        } else if (pageTotal > 7 && page <= 4) {

            for (var i = 1; i <= 7; i++) {

                if (i == page) {

                    pageStr += '<span class="current btn btn-primary active radius-none">' + i + '</span>';

                } else {

                    pageStr += '<a href="javascript:;" data-src="' + src + '" data-page="' + i + '" class="num btn btn-default radius-none _page">' + i + '</a>';

                }

            }

            pageStr += '<a href="javascript:;" data-src="' + src + '" data-page="' + pageTotal + '" class="num btn btn-default radius-none _page">' + pageTotal + '</a>';

        } else if (pageTotal > 7 && page > 4 && page <= (pageTotal - 4)) {

            for (var i = (page - 3); i <= (page + 3); i++) {

                if (i == page) {

                    pageStr += '<span class="current btn btn-primary active radius-none">' + i + '</span>';

                } else {

                    pageStr += '<a href="javascript:;" data-src="' + src + '" data-page="' + i + '" class="num btn btn-default radius-none _page">' + i + '</a>';

                }

            }

            pageStr += '<a href="javascript:;" data-src="' + src + '" data-page="' + pageTotal + '" class="num btn btn-default radius-none _page">' + pageTotal + '</a>';

        } else if (pageTotal > 7 && page > (pageTotal - 4) && page <= pageTotal) {

            for (var i = (pageTotal - 7); i <= pageTotal; i++) {

                if (i == page) {

                    pageStr += '<span class="current btn btn-primary active radius-none">' + i + '</span>';

                } else {

                    pageStr += '<a href="javascript:;" data-src="' + src + '" data-page="' + i + '" class="num btn btn-default radius-none _page">' + i + '</a>';

                }

            }

        }

        if (page < pageTotal) {
            pageStr += '<a href="javascript:;" data-src="' + src + '" data-page="' + (page + 1) + '" class="num btn btn-default radius-none _page">下一页</a>';
            pageStr += '<a href="javascript:;" data-src="' + src + '" data-page="' + pageTotal + '" class="num btn btn-default radius-none _page">尾页</a>';
        }
        if (pageTotal > 7) {
            pageStr += '<select id="_select_page" data-src="' + src + '" style="float: left;;padding: 5px 12px;border: 1px solid #ccc;border-left: none;font-size:14px;">';

            for (var i = 1; i <= pageTotal; i++) {

                var selected = '';

                if (i == page)
                    selected = ' selected="selected" ';

                pageStr += '<option' + selected + ' value="' + i + '">第' + i + '页</option>';


            }

            pageStr += '</select>';
        }

        $pages.html(pageStr);

        _pageEvents(options);


    }
    var _pageEvents = function (options) {


        var options = options ? options : {};

        $('#_select_page').change(function () {


            options.page = $(this).val();

            //获取请求连接
            var src = $(this).data('src');


            //显示加载动画
            var timeOut = setTimeout(function () {

                layer.load();

            }, 500);
            //请求数据
            $('#main-content').load(src, options, function () {

                clearTimeout(timeOut);
                layer.closeAll();

            })

        })

        $('._page').unbind('click');

        $('._page').click(function () {

            //if(typeof options != 'object')
            //    var options = {};
            //获取当前页码
            options.page = $(this).data('page');

            //获取请求连接
            var src = $(this).data('src');


            //显示加载动画
            var timeOut = setTimeout(function () {

                layer.load();

            }, 500);
            //请求数据
            $('#main-content').load(src, options, function () {

                clearTimeout(timeOut);
                layer.closeAll();

            })


        });

    }

    var action = function (level, isLoad, menuid, _this, menuNode) {
        //获取当前菜单等级
        //var level = level ? level : $(this).data('level');
        //获取是否拥有自己
        //获取菜单等级
        var level = level ? level : 1;

        var menuNode = menuNode ? menuNode : '.menu';

        //获取节点对象
        var _this = _this ? _this : $('#menu' + level).children().first().children();

        if (level == 3 && _this.parent().hasClass('have-child')) {
            var _this = _this
                .next()
                .children()
                .first()
                .children();
        }

        //是否加载子级
        var isLoad = isLoad ? isLoad : _this.data('loadchild');

        //获取菜单ID
        var menuid = menuid ? menuid : _this.data('id');


        //切换当前节点操作状态
        if (level == 3) {
            $('.have-child > ul > li').each(function () {

                $(this).removeClass('active');

            });

        } else if (level == 4) {

            _this
                .parent()
                .parent()
                .parent()
                .siblings()
                .removeClass('active');


        }
        _this
            .parent()
            .addClass('active')
            .siblings()
            .removeClass('active');

        //如果不加载自己则加载页面
        if (isLoad == 0) {

            var src = _this.data('src');

            //清除缓存或变量
            clear();


            var timeOut = setTimeout(function () {

                layer.load();

            }, 500);



            $('#main-content').load(src, function (result) {

                clearTimeout(timeOut);
                layer.closeAll();

                try{

                    var result = JSON.parse(result);
                    layer.msg(result.msg, {offset: 50, shift: 6, time: 3000}, function () {

                        window.location.href = result.url;

                    });

                    return false;

                }catch(err){

                    $('#main-title')
                        .text(
                        $('#menu' + level + ' li.active')
                            .children()
                            .data('name')
                    );

                    if (level == 1) {

                        hideOrShow('hide', 'hide');

                    } else if (level == 2) {

                        hideOrShow('show', 'hide');

                    } else {

                        hideOrShow('show', 'show');

                    }
                }


            });
            // document.getElementById('main').src = src;

            return false;


        } else {

        }

        //加载菜单
        loadMenu('#menu' + (level + 1), menuid, level);
    }

    /*
     ** @introduction: 加载菜单
     ** @author: 杨陈鹏
     ** @date: 2015-03-26 13：04
     ** @email: yangchenpeng@cdlinglu.com
     */

    var loadMenu = function (pElement, menuid, level) {

        var timeOut = setTimeout(function () {

            layer.load();

        }, 500);

        var nextLevel = level ? level + 1 : 1;

        $(pElement).load(loadMenuUrl, {'menuid': menuid, 'level': level}, function (result) {

            clearTimeout(timeOut);
            layer.closeAll();

            try
            {
                var result = JSON.parse(result);
                layer.msg(result.msg, {offset: 50, shift: 6, time: 3000}, function () {

                    window.location.href = result.url;

                });

                return false;

            }catch(err)
            {

                if ( typeof data == 'object' ) {

                    layer.msg(result.msg, {offset: 50, shift: 6, time: 3000}, function () {

                        window.location.href = result.url;

                    });

                    return false;

                }

                if (level == 2) {

                    var name = $('#menu' + level + ' li.active a').data('name');

                    $('#second-title').text(name)

                }

                action(nextLevel);

            }

        });

    }
    /*
     ** @introduction: 显示或隐藏侧边栏
     ** @author: 杨陈鹏
     ** @date: 2015-03-26 13：04
     ** @email: yangchenpeng@cdlinglu.com
     */
    var hideOrShow = function (s1, s2) {
        var s1 = s1 ? s1 : 'show';
        var s2 = s2 ? s2 : 'show';
        //操作一级侧边栏
        if (s1 == 'show') {
            $('.body')
                .removeClass('sidebar-mini')
                .addClass('sidebar-full');
            $('.sidebar-content>.sidebar-fold').html('<span class="glyphicon glyphicon-triangle-right" aria-hidden="true"></span><span class="glyphicon glyphicon-triangle-left" aria-hidden="true"></span>');
        } else if (s1 == 'hide') {
            $('.body')
                .removeClass('sidebar-full')
                .addClass('sidebar-mini');
            $('.sidebar-content>.sidebar-fold').html('<span class="glyphicon glyphicon-triangle-left" aria-hidden="true"></span><span class="glyphicon glyphicon-triangle-right" aria-hidden="true"></span>');
        }
        //操作二级侧边栏
        //操作一级侧边栏
        if (s2 == 'show') {
            $('.main')
                .removeClass('main-sidebar-hide')
                .addClass('main-sidebar-show');
        } else if (s2 == 'hide') {
            $('.main')
                .removeClass('main-sidebar-show')
                .addClass('main-sidebar-hide');
        }
    }
    /*
     ** @introduction: 显示当前系统时间
     ** @author: 杨陈鹏
     ** @date: 2015-03-28 09:30
     ** @email: yangchenpeng@cdlinglu.com
     */
    var showTime = function (seperator1, seperator2) {

        var date = new Date();
        var seperator1 = seperator1 ? seperator1 : "/";
        var seperator2 = seperator2 ? seperator2 : ":";
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();

        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (day >= 0 && day <= 9) {
            day = "0" + day;
        }
        if (hour >= 0 && hour <= 9) {
            hour = "0" + hour;
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }

        //var timeStr = date.getFullYear() + seperator1 + month + seperator1 + day
        //+ " " + hour + seperator2 + minutes
        //+ seperator2 + seconds;
        return date.getFullYear() + seperator1 + month + seperator1 + day
            + " " + hour + seperator2 + minutes
            + seperator2 + seconds;

    }

    /*
     ** @introduction: ajax请求
     ** @author: 杨陈鹏
     ** @date: 2015-03-26 12：58
     ** @email: yangchenpeng@cdlinglu.com
     ** @param: requestUrl string 请求地址
     ** @param: method string 请求方式
     ** @param: data object 请求参数
     ** @param: id string 节点ID
     */
    var _ajaxRequest = function (requestUrl, method, data, id, _this) {


        $.ajax({

            url: requestUrl,

            type: method,

            data: {'data': data},

            dataType: "json",

            success: function (result) {

                layer.closeAll();

                if (typeof ajaxRequestCallback == 'function') {

                    ajaxRequestCallback(result, id, _this);

                } else {

                    if (typeof result == 'String')
                        result = JSON.parse(result);

                    layer.msg(result.msg);

                }

            }

        });
    }

    return {


        /*
         ** @introduction: 实例化百度编辑器
         ** @author: 杨陈鹏
         ** @date: 2015-03-26 12：58
         ** @email: yangchenpeng@cdlinglu.com
         ** @param:  string  id 编辑器实例化ID
         ** @param: function 回调函数
         */
        getUeditor: function (id, callback) {

            UE.delEditor(id);


            //实例化百度编辑器
            var ue = UE.getEditor(id, {
                autoHeight: true,
                autoFloatEnabled: false,
                UEDITOR_HOME_URL: editor.path,
                initialFrameWidth: '100%',  //初化编辑器宽度,默认1000
                initialFrameHeight: 500,  //初始化编辑器高度,默认320
                toolbars: [[
                    'undo', 'redo', '|',
                    'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'blockquote', 'backcolor', '|',
                    'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                    'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                    'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                    'insertimage', 'emotion', 'map', 'background','get_goods_info'
                ]]
            });

            if (typeof callback == 'function') {

                callback(ue);

            } else if (typeof getEditorCallback == 'function') {

                getEditorCallback(ue);


            }


        },
        /*
         ** @introduction: 自动生成分页页码
         ** @author: 杨陈鹏
         ** @date: 2015-03-26 12：58
         ** @email: yangchenpeng@cdlinglu.com
         */
        pages: function (options) {

            _pages(options)

        },
        /*
         ** @introduction: 隐藏侧边栏
         ** @author: 杨陈鹏
         ** @date: 2015-03-26 12：58
         ** @email: yangchenpeng@cdlinglu.com
         */
        sidebar: function () {
            //一级侧边栏
            $('.sidebar-fold').unbind('click');
            $('.sidebar-fold').click(function () {
                if ($('.body').hasClass('sidebar-full')) {
                    $('.body').removeClass('sidebar-full').addClass('sidebar-mini');
                    $(this).html('<span class="glyphicon glyphicon-triangle-left" aria-hidden="true"></span><span class="glyphicon glyphicon-triangle-right" aria-hidden="true"></span>');
                } else {
                    $('.body').removeClass('sidebar-mini').addClass('sidebar-full');
                    $(this).html('<span class="glyphicon glyphicon-triangle-right" aria-hidden="true"></span><span class="glyphicon glyphicon-triangle-left" aria-hidden="true"></span>');
                }
            });
            //二级侧边栏
            $('.action').unbind('click');
            $('.action').click(function () {
                var $parent = $(this).parent();
                if ($parent.hasClass('main-sidebar-show')) {
                    $parent.removeClass('main-sidebar-show').addClass('main-sidebar-hide');
                } else {
                    $parent.removeClass('main-sidebar-hide').addClass('main-sidebar-show');
                }
            });
            //二级侧边栏折叠
            $('.main-sidebar-list').delegate('li.have-child > a', 'click', function (event) {
                event.preventDefault();  //阻止连接跳转
            });
            $('.main-sidebar-list').undelegate('li.have-child > a', 'click');
            $('.main-sidebar-list').delegate('li.have-child > a', 'click', function () {

                if ($(this).parent().hasClass('_hide')) {
                    $(this)
                        .parent()
                        .removeClass('_hide')
                        .addClass('_show');
                } else {
                    $(this)
                        .parent()
                        .removeClass('_show')
                        .addClass('_hide');
                }
            });
        },

        Time: function () {

            var _this = this;

            //一秒刷新一次显示时间
            setInterval(function () {

                $('#time').text('当前时间:' + _this.getTime());

            }, 1000);


        },
        getTime: function (separator1, separator2) {

            return showTime(separator1, separator2);

        },
        //节点操作请求
        _noteAjax: function (eventNote) {

            var eventNote = eventNote ? eventNote : '._ajaxNote';

            $('.main-body').undelegate(eventNote, 'click');

            $('.main-body').delegate(eventNote, 'click', function () {

                var _this = $(this);


                var msg = _this.data('msg') ? _this.data('msg') : false;


                var data = _this.data('data');

                var requestUrl = _this.data('src') ? _this.data('src') : '';

                var method = _this.data('method') ? _this.data('method') : 'post';

                var id = _this.data('id');


                if (msg) {

                    layer.msg(msg, {
                        time: 0,
                        btn: ['确定', '关闭'],
                        yes: function (i) {

                            layer.close(i);

                            _ajaxRequest(requestUrl, method, data, id, _this);

                        }
                    });

                } else {

                    _ajaxRequest(requestUrl, method, data, id, _this);

                }

            });

        },

        /*
         ** @introduction: 异步加载菜单
         ** @author: 杨陈鹏
         ** @date: 2015-03-26 12：58
         ** @email: yangchenpeng@cdlinglu.com
         ** @param: menuNode  string 菜单节点类
         */

        menuEvent: function (menuNode) {

            action();
            menuEvents(menuNode);

        },
        /*
         ** @introduction: 异步加载菜单
         ** @author: 杨陈鹏
         ** @date: 2015-03-26 12：58
         ** @email: yangchenpeng@cdlinglu.com
         ** @param: note  string 触发点击事件的节点
         ** @param: type  string 上传类型,单图上传 or 多图上传
         */
        upload: function (note, type, callback) {

            var note = note ? note : '#thumb';

            var up_src = type ? UP_MANY_SRC_IFREAME : UP_ONE_SRC_IFREAME;

            $('body').undelegate(note, 'click');//unbind('click');

            $('body').delegate(note, 'click', function () {
                layer.open({
                        type: 2,
                        title: '图像上传',
                        shadeClose: true,
                        shade: 0.8,
                        area: ['80%', '80%'],
                        content: up_src, //iframe的url
                    }
                );

                if (typeof callback == 'function') {

                    callback($(this));

                } else if (typeof thumbUploadCallback == 'function') {

                    thumbUploadCallback($(this));

                }

            });

        },
        /*
         ** @introduction: ajax数据请求
         ** @author: 杨陈鹏
         ** @date: 2015-03-26 12：58
         ** @email: yangchenpeng@cdlinglu.com
         ** @param: menuNode  string 菜单节点类
         */
        ajaxRequest: function (className, dataClassName) {

            this._noteAjax();

            var className = className ? className : 'form._ajaxSubmit';

            var dataClassName = dataClassName ? dataClassName : '._data';


            $('.main-body').undelegate(className, 'submit');

            $('.main-body').delegate(className, 'submit', function () {

                var _this = $(this);

                var data = {};

                var requestUrl = _this.attr('action');

                var id = _this.attr('id');

                var method = _this.attr('method');

                $(dataClassName).each(function (i, v) {

                    if ($(this).attr('type') == 'radio') {

                        if ($(this).is(':checked'))
                            data[$(this).attr('name')] = $(this).val();

                        // }else if($(this).attr('type') == 'checkbox'){

                        //     if($(this).is(':checked'))
                        //         data[$(this).attr('name')] += $(this).val()+',';

                    } else {

                        data[$(this).attr('name')] = $(this).val();

                    }

                });

                _ajaxRequest(requestUrl, method, data, id, _this);

                return false;

            });
        }

    }
}();

/**
 * @introduction: 清除
 * @author: 杨陈鹏
 * @date: 2015-03-26 12：58
 * @email: yangchenpeng@cdlinglu.com
 */
function clear() {


    //清楚服务器时时请求
    if (typeof serverTimeout != 'undefined')
        clearTimeout(serverTimeout);


}


/**
 * @introduction: 显示提示信息和页面跳转
 * @author: 杨陈鹏
 * @date: 2015-03-26 12：58
 * @email: yangchenpeng@cdlinglu.com
 * @param:msg String or Object 字符串时为提示信息,  对象时为所有信息
 * @param:code  状态
 * @param:url 跳转地址
 * @param:data 跳转时的post参数
 * @param:time 跳转等待时间  默认不等待
 * @param:errorCallback 失败回掉地址  默认2s
 * @param:seccessCallback 成功调函数
 */
function showMessage(msg, code, url, data, time, seccessCallback, errorCallback) {


    if (typeof msg != 'string') {

        var code = msg.code ? msg.code : false;//200成功状态,300失败状态

        var data = msg.data ? msg.data : {};

        var url = msg.url ? msg.url : false;

        var time = msg.time ? msg.time : 1;

        var msg = msg.msg ? msg.msg : '';

    } else {

        var code = code ? code : false;//200成功状态,300失败状态

        var data = data ? data : {};

        var url = url ? url : false;

        var time = time ? time : 1;

        var msg = msg ? msg : '';

    }
    switch (code) {

        case 200:

            layer.msg(msg, {time: time,shift:1, offset: 50}, function () {

                if (url)
                    _load(url, data, seccessCallback, errorCallback);

            });

            break;

        case 300:

            layer.msg(msg, {time: time, offset: 50, shift: 6}, function () {

                if (url)
                    _load(url, data, seccessCallback, errorCallback);

            });

            break;

        default :

            if (url)
                _load(url, data, seccessCallback, errorCallback);

            break;

    }

    return false;


}

function _load(url, data, seccessCallback, errorCallback) {



    //显示加载动画
    var timeOut = setTimeout(function () {

        layer.load();

    }, 500);


    $('#main-content').load(url, data, function (result, status, xhr) {

        clearTimeout(timeOut);
        layer.closeAll();

        if (status == 'success') {

            if (typeof seccessCallback == 'function') {

                seccessCallback(result);

            } else if (typeof showMessageCallback == 'function') {

                showMessageCallback(result);

            }

        } else {


            if (typeof errorCallback == 'function') {

                errorCallback();

            } else if (typeof showMessageErrorCallback == 'function') {

                showMessageErrorCallback(result);

            }
        }

    });
}
/**
 * @introduction: 剪切URL路径，组装需要规格的图片地址
 * @author: 杨陈鹏
 * @date: 2015-03-26 12：58
 * @email: yangchenpeng@cdlinglu.com
 * @param:url String 图片地址
 * @param:width Number 图片宽度
 * @param:height Number 图片高度
 */
function cutUrl(url, width, height) {

    var d = '_' + width + '_' + height;

    if (url.indexOf(d) < 0) {

        var idx = url.lastIndexOf('.');
        url = url.substr(0, idx) + d + url.substr(idx);

    }

    return url;


}